Ext.ns('App')
Ext.ns('ISales')
Ext.ns('ISales.Portals')
Ext.ns('ISales.grids')
Ext.ns('ISales.fieldsets')
Ext.ns('Ext.DataView')




ISales.SettingsToolbar = Ext.extend(Ext.Toolbar, {
    cls: 'minimalistic',
    i18n: {
        'workflowmenu': 'Workflow settings',
        'keywordsmenu': 'Keywords',
        'alldocumentsmenu': 'All documents',
        'menumenu': 'Menu builder',
        'logoutmenu': 'Log out'
    },
    initComponent: function(){
        Ext.applyIf(this, {
            items: ['->', {
                iconCls: 'Icon_Settings',
                iconAlign: 'right',
                arrowAlign: 'left',
                menu: [{
                    iconCls: 'Icon_FolderEdit',
                    text: this.i18n['menumenu'],
                    tabTitle: this.i18n['menumenu'],
                    tabId: 'pnl-menus',
                    tabXtype: 'menuadministrationui',
                    handler: this.tabOpener.createDelegate(this)
                }, {
                    iconCls: 'Icon_Key',
                    text: this.i18n['keywordsmenu'],
                    tabTitle: this.i18n['keywordsmenu'],
                    tabId: 'pnl-keywords',
                    tabXtype: 'keywordsgrid',
                    handler: this.tabOpener.createDelegate(this)
                }, {
                    iconCls: 'Icon_View',
                    text: this.i18n['alldocumentsmenu'],
                    tabTitle: this.i18n['alldocumentsmenu'],
                    tabId: 'pnl-alldocuments',
                    tabXtype: 'alldocumentsgrid',
                    handler: this.tabOpener.createDelegate(this)
                
                }, {
                    iconCls: 'Icon_View',
                    text: 'Nyanställning',
                    tabTitle: 'Nyanställning',
                    tabId: 'pnl-sampledocuments',
                    tabXtype: 'samplegrid',
                    handler: this.tabOpener.createDelegate(this)
                
                }, {
                    iconCls: 'Icon_View',
                    text: 'Workflow',
                    tabTitle: 'Workflowinställningar',
                    tabId: 'pnl-workflowsettings',
                    tabXtype: 'workflowui',
                    handler: this.tabOpener.createDelegate(this)
                
                },'-', {
                    text: this.i18n['logoutmenu']
                }]
            }]
        })
        ISales.SettingsToolbar.superclass.initComponent.apply(this, arguments);
    },
    tabOpener: function(menu){
        target = Ext.getCmp(this.target)
        if (!Ext.getCmp(menu.tabId)) {
            target.add({
                iconCls: menu.iconCls,
                xtype: menu.tabXtype,
                title: menu.tabTitle,
                closable: true,
                id: menu.tabId
            });
            target.setActiveTab(menu.tabId)
        }
    }
});

ISales.Portals.Layout1 = Ext.extend(Ext.Panel, {
    i18n: {
        'box1title': 'box1',
        'box2title': 'box2',
        'box3title': 'box3',
        'box4title': 'box4'
    },
    
    
    initComponent: function(){
    
        Ext.applyIf(this, {
            layout: 'vbox',
            border: false,
            defaults: {
                border: false
            },
            layoutConfig: {
                align: 'stretch',
                pack: 'start'
            },
            items: [{
                flex: 1,
                layout: 'hbox',
                layoutConfig: {
                    align: 'stretch',
                    pack: 'start'
                },
                items: [{
                    flex: 1,
                    margins: '10 10 10 10',
                    title: this.i18n['box1title']
                }, {
                    flex: 1,
                    margins: '10 10 10 10',
                    title: this.i18n['box2title']
                }]
            
            }, {
                flex: 1,
                layout: 'hbox',
                layoutConfig: {
                    align: 'stretch',
                    pack: 'start'
                },
                items: [{
                    flex: 1,
                    margins: '10 10 10 10',
                    title: this.i18n['box3title']
                }, {
                    flex: 1,
                    margins: '10 10 10 10',
                    title: this.i18n['box4title']
                }]
            
            }]
        })
        ISales.Portals.Layout1.superclass.initComponent.apply(this, arguments);
    }
});
Ext.reg('isalesportallayout1', ISales.Portals.Layout1);


ISales.SearchView = Ext.extend(Ext.Panel, {
    //override for other languages
    title: 'Global Search',
    i18n: {
        'options': 'Options',
        'include_contacts': 'Include contacts',
        'include_companies': 'Include companies'
    },
    
    initComponent: function(){
    
        this.addEvents('ItemClicked')
        
        this.s = new Ext.data.Store({
            proxy: new Ext.data.ScriptTagProxy({
                url: 'http://solr.i-seven.com:8080/solrdev/select/?',
                method: 'GET',
                callbackParam: 'json.wrf'
            }),
            baseParams: {
                //q: '*',
                version: '2.2',
                rows: 10000,
                indent: 'on',
                sort: 'subject asc',
                wt: 'json'
                // fq: 'doctype:clCompanyProfile doctype:clContactProfile'
            },
            reader: new Ext.data.JsonReader({
                root: "response.docs",
                id: "id",
                idProperty: "id",
                successProperty: "success",
                totalProperty: "response.numFound",
                fields: ["id", "row1", "row2", "row3", "doctype"]
            }),
            paramNames: {
                start: 'start',
                limit: 'rows'
            },
            remoteSort: true,
            sortInfo: {
                field: 'row1',
                direction: 'ASC'
            },
            listeners: {
                'beforeload': this.beforeLoad.createDelegate(this),
                'load': this.afterSearch.createDelegate(this),
                'clear': this.clearResult.createDelegate(this),
                scope: this
            
            }
        
        });
        
        this.Tpl = new Ext.XTemplate('<tpl for=".">', '<div class="search-item {doctype}">', '<span><b>{row1}</b></span><br>', '{row2}<BR>{row3}', '</div></tpl>');
        
        Ext.applyIf(this, {
            bodyStyle: 'padding:10px',
            autoScroll: true,
            layout: 'vbox',
            layoutConfig: {
                align: 'stretch'
            },
            items: [{
                height: 50,
                layout: 'vbox',
                border: false,
                layoutConfig: {
                    align: 'stretch'
                },
                items: [new ExtArc.SolR.SearchField({
                    id: 'searchfield',
                    selectOnFocus: true,
                    flex: 1,
                    bodyStyle: 'padding:10px',
                    store: this.s,
                    width: 200
                }), new Ext.Toolbar({
                    cls: 'minimalistic',
                    flex: 1,
                    items: [{
                        id: 'search-result-info',
                        xtype: 'label',
                        border: false,
                        text: '',
                        cls: 'search-result-info'
                    }, '->', {
                        id: 'filtermenu',
                        xtype: 'button',
                        border: false,
                        text: this.i18n['options'],
                        
                        menu: [new ExtArc.SolR.FilterCheckbox({
                            flex: 1,
                            store: this.s,
                            boxLabel: this.i18n['include_companies'],
                            querystring: 'doctype:clCompanyProfile'
                        
                        }), new ExtArc.SolR.FilterCheckbox({
                            store: this.s,
                            flex: 1,
                            boxLabel: this.i18n['include_contacts'],
                            querystring: 'doctype:clContactProfile'
                        
                        })]
                    }]
                })]
            }, {
                flex: 1,
                autoScroll: true,
                border: false,
                items: [new Ext.DataView({
                    id: 'searchdataview',
                    flex: 1,
                    autoScroll: true,
                    tpl: this.Tpl,
                    store: this.s,
                    itemSelector: 'div.search-item',
                    overClass: 'x-view-over',
                    singleSelect: true,
                    
                    listeners: {
                        'click': this.ItemClick.createDelegate(this),
                        scope: this
                    }
                })]
            }]
        })
        ISales.SearchView.superclass.initComponent.apply(this, arguments);
    },
    ItemClick: function(dataview, index, htmlEl, e){
        var record = dataview.getRecord(htmlEl);
        this.fireEvent('ItemClicked', record.get('doctype'), record.get('id'), htmlEl);
    },
    afterSearch: function(store, records, options){
        var resp = store.reader.jsonData.response
        Ext.getCmp('search-result-info').setText(resp.numFound + ' hits.')
        var v = Ext.getCmp('searchdataview')
        v.dragZone = new Ext.dd.DragZone(v.getEl(), {
            ddGroup: 'FavDD',
            getDragData: function(e){
                var sourceEl = e.getTarget(v.itemSelector, 10);
                if (sourceEl) {
                    d = sourceEl.cloneNode(true);
                    d.id = Ext.id();
                    return {
                        sourceEl: sourceEl,
                        repairXY: Ext.fly(sourceEl).getXY(),
                        ddel: d,
                        recordData: v.getRecord(sourceEl)
                    }
                }
            },
            getRepairXY: function(){
                //console.log('reapir')
                return this.dragData.repairXY;
            }
            
        });
        
    },
    clearResult: function(store){
        Ext.getCmp('search-result-info').setText('')
    },
    beforeLoad: function(store, opt){
        filtermenu = Ext.getCmp('filtermenu')
        var pos
        var fqArr = [];
        filtermenu.menu.items.each(function(item){
            if (item.checked) {
                pos = fqArr.push(item.querystring);
            }
            else {
                pos = fqArr.push('-' + item.querystring);
            }
        }, this);
        Ext.apply(opt.params, {
            fq: fqArr.join(' ')
        
        });
        
    }
})
Ext.reg('isalessearchview', ISales.SearchView);


App.SampleGrid = Ext.extend(Ext.grid.GridPanel, {
    initComponent: function(){
        Ext.apply(this, {
            enableDragDrop: true,
            ddGroup: 'FavDD',
            bodyStyle: 'border:1px solid #c9c9c9',
            store: new Ext.data.Store({
                proxy: new Ext.data.HttpProxy({
                    method: 'GET',
                    url: 'ag.ExtArc.ApplicationTemplate?Openagent'
                }),
                baseParams: {
                    xaction: 'loadsampledocuments'
                },
                reader: new Ext.data.JsonReader({
                    root: 'root',
                    totalProperty: 'totalcount',
                    fields: ['fdDocumentDescription', 'fdDocumentClass', 'fdDocumentKey', 'fdCreatedBy', 'fdName', 'fdPhone', 'fdCreated']
                }),
                autoLoad: true,
                storeId: 'SampleDocumentStore'
            }),
            columns: [{
                header: "Namn",
                dataIndex: 'fdName'
            }, {
                header: "Telefon",
                dataIndex: 'fdPhone'
            }],
            viewConfig: {
                forceFit: true
            },
            sortInfo: {
                field: 'fdName',
                direction: 'DESC'
            },
            tbar: new Ext.Toolbar({
                //cls: 'whitetoolbar',
				cls: 'cleantoolbar',
                border: false,
                items: [new Ext.Button({
                    text: 'Skapa ny',
                    cls: 'mybutton',
                    minWidth: 100,
                    handler: this.addDocument,
                    scope: this
                })]
            })
        })
        App.SampleGrid.superclass.initComponent.apply(this, arguments);
    },
    onRender: function(ct, position){
        App.SampleGrid.superclass.onRender.apply(this, arguments);
        this.on('rowdblclick', this.openDocument, this);
        this.on('rowcontextmenu', this.onRightClick, this);
        
    },
    onRightClick: function(grid, rowIndex, e){
        e.stopEvent();
        grid.getSelectionModel().selectRow(rowIndex, true);
        var menu = new Ext.menu.Menu({
            id: 'xnd-context-menu'
        });
        menu.add({
            text: 'Delete',
            iconCls: 'deleteicon',
            handler: this.deleteDocuments,
            grid: grid,
            scope: this
        });
        var coords = e.getXY();
        menu.showAt([coords[0], coords[1]]);
        
    },
    deleteDocuments: function(menu){
        sm = menu.grid.getSelectionModel();
        records = sm.getSelections();
        var arrUnid = new Array(records.length);
        for (var i = 0; i < records.length; i++) {
            arrUnid[i] = records[i].data.fdDocumentKey;
        }
        if (arrUnid.length < 1) {
            alert('You need to select at least one row (left click)');
        }
        else {
            Ext.Msg.show({
                title: 'Are you Sure??',
                msg: 'You are about to <B>delete ' + arrUnid.length + ' document(s)</B>. Are you sure?',
                buttons: Ext.Msg.YESNO,
                icon: Ext.Msg.QUESTION,
                fn: function(btn, text){
                    if (btn == 'yes') {
                        var myMask = new Ext.LoadMask(Ext.getBody(), {
                            msg: "Please wait...Deleting documents"
                        });
                        myMask.show();
                        
                        Ext.Ajax.request({
                            url: 'ag.ExtArc.ApplicationTemplate?Openagent',
                            scope: this,
                            success: function(response){
                                menu.grid.store.load();
                                myMask.hide();
                            },
                            params: {
                                xaction: 'DeleteSampleDocuments',
                                unids: arrUnid.join(",")
                            
                            }
                        });
                    }
                }
            });
        }
    },
    openDocument: function(grid, row, e){
        var record = grid.getStore().getAt(row);
        
        
        ISalesGlobal.ui.tabPanel.add({
            title: 'Uppgifter',
            height: 400,
            closable: true,
            width: 600,
            layout: 'fit',
            monitorValid: true,
            items: [{
                id: 'pnl-' + record.data.fdDocumentKey,
                xtype: 'sampledocumentform',
                grid: this,
                unid: record.data.fdDocumentKey
            }]
        }).show()
        
        /*
         new Ext.Window({
         title: 'Sample DOcument',
         height: 400,
         width: 600,
         layout: 'fit',
         monitorValid: true,
         items: [{
         id: 'pnl-' + record.data.fdDocumentKey,
         xtype: 'sampledocumentform',
         grid: this,
         unid: record.data.fdDocumentKey
         }]
         
         }).show();
         */
    },
    addDocument: function(){
        /*
new Ext.Window({
            title: 'New Sample DOcument',
            height: 400,
            width: 600,
            layout: 'fit',
            monitorValid: true,
            items: [{
                id: 'pnl-',
                xtype: 'sampledocumentform',
                grid: this
            }]
        }).show();
*/
		
		
		ISalesGlobal.ui.tabPanel.add({
            title: 'Nyanställd',
            height: 400,
            closable: true,
            width: 600,
            layout: 'fit',
            monitorValid: true,
            items: [{
                id: 'pnl-',
                xtype: 'sampledocumentform',
                grid: this
               

            }]
        }).show()
    }
});
Ext.reg('samplegrid', App.SampleGrid);


App.SampleDocumentForm = Ext.extend(ExtArc.Workflow.Form, {
    initComponent: function(){
        Ext.apply(this, {
        
            agentPath: 'ag.ExtArc.ApplicationTemplate?Openagent',
            loadAction: 'loadsampledocument',
            saveAction: 'savesampledocument',
            
            
            bodyStyle: 'background-color:transparent;padding:10px',
            border: false,
            labelAlign: 'top',
            monitorValid: true,
            defaults: {
                anchor: '100%',
                xtype: 'textfield'
            },
            items: [{
                fieldLabel: 'Namn',
                allowBlank: false,
                name: 'fdName'
            }, {
                fieldLabel: 'Telefon',
                name: 'fdPhone',
                allowBlank: false
            }, {
                fieldLabel: 'E-Post',
                name: 'fdEmail',
                allowBlank: false
            }, {
                xtype: 'keywordcombo',
                kw: 'kwCities',
                fieldLabel: 'Kontor',
                name: 'fdCity'
            
            }/*
, {
                xtype: 'promptnamemulti',
                fieldLabel: 'Multiple names',
                name: 'fdmultinames'
            }, {
                xtype: 'promptnamesingle',
                fieldLabel: 'Single name',
                name: 'fdsinglenames'
            }
*/]
        });
        App.SampleDocumentForm.superclass.initComponent.apply(this, arguments);
    }
});
Ext.reg('sampledocumentform', App.SampleDocumentForm);
Ext.reg('clSampleDocument', App.SampleDocumentForm);


ISales.fieldsets.Categories = Ext.extend(Ext.form.FieldSet, {

    fieldlabels: {
        'categories': 'Categories',
        'status': 'Status',
        'type': 'Type',
        'industry': 'Industry',
        'group': 'Group',
        'lob': 'Line of Business'
    },
    
    initComponent: function(){
    
    
    
        Ext.apply(this, {
            title: this.fieldlabels['categories'],
            collapsible: true,
            autoHeight: true,
            defaults: {
                width: 210,
                server: ISales.Connections['server'],
                path: ISales.Connections['path'],
                classField: 'cls',
                labelSeparator: ''
            
            },
            defaultType: 'textfield',
            
            items: [{
                fieldLabel: this.fieldlabels['status'],
                xtype: 'keywordmultiselector',
                name: 'fdcompanystatus',
                extraItemCls: 'superboxitem-withicons',
                displayFieldTpl: '<B>{fdalias}</B>',
                kw: 'kwcompanystatus',
                listCls: 'orangeBullet'
            }, {
                xtype: 'keywordmultiselector',
                name: 'fdcompanytype',
                kw: 'kwCompanyTypes',
                displayFieldTpl: '{fdalias}',
                fieldLabel: this.fieldlabels['type']
            
            }, {
                xtype: 'keywordmultiselector',
                name: 'fdcompanyindustry',
                displayFieldTpl: '{fdalias}',
                fieldLabel: this.fieldlabels['industry'],
                kw: 'kwCompanyIndustry',
                extraItemCls: 'superboxitem-withicons',
                listCls: 'clCompanyProfile'
            }, {
                xtype: 'keywordmultiselector',
                name: 'fdcompanylob',
                displayFieldTpl: '{fdalias}  ',
                fieldLabel: this.fieldlabels['lob'],
                kw: 'kwCompanyLOB'
            }, {
                xtype: 'keywordmultiselector',
                name: 'fdcompanygroup',
                displayFieldTpl: '{fdalias}',
                kw: 'kwCompanyGroup',
                fieldLabel: this.fieldlabels['group']
            }]
        })
        ISales.fieldsets.Categories.superclass.initComponent.apply(this, arguments);
    }
})

Ext.reg('fieldsetcategories', ISales.fieldsets.Categories);

ISales.fieldsets.Responsible = Ext.extend(Ext.form.FieldSet, {

    fieldlabels: {
        'responsible': 'Responsible',
        'sales': 'Sales responsible',
        'salesbackup': 'Backup sales responisble',
        'tech': 'Technical responsible',
        'techbackup': 'Backup technical responsible'
    },
    initComponent: function(){
    
    
    
        Ext.apply(this, {
            title: this.fieldlabels['responsible'],
            collapsible: true,
            autoHeight: true,
            defaults: {
                width: 210,
                server: ISales.Connections['namesServer'],
                path: ISales.Connections['namesPath'],
                extraItemCls: 'superboxitem-withicons',
                classField: 'cls',
                displayFieldTpl: '{fdalias}',
                labelSeparator: ''
            },
            defaultType: 'textfield',
            
            items: [{
                fieldLabel: this.fieldlabels['sales'],
                xtype: 'namessuperbox',
                name: 'fdsalesperson',
                listCls: 'clContactProfile'
            }, {
                fieldLabel: this.fieldlabels['salesbackup'],
                xtype: 'namessuperbox',
                name: 'fdbackupsalesperson',
                listCls: 'clContactProfile'
            }, {
                fieldLabel: this.fieldlabels['tech'],
                xtype: 'namessuperbox',
                name: 'fdtechnicalresponsible',
                listCls: 'clContactProfile'
            }, {
                fieldLabel: this.fieldlabels['techbackup'],
                xtype: 'namessuperbox',
                name: 'fdbackuptechnicalresponsible',
                listCls: 'clContactProfile'
            }]
        })
        ISales.fieldsets.Responsible.superclass.initComponent.apply(this, arguments);
    }
})

Ext.reg('fieldsetresponsible', ISales.fieldsets.Responsible);


ISales.fieldsets.Contactinfo = Ext.extend(Ext.form.FieldSet, {

    fieldlabels: {
        'contactinfo': 'Contact information',
        'jobtitle': 'Job title',
        'salutation': 'Salutation',
        'firstname': 'First name',
        'middlename': 'Middle name',
        'lastname': 'Last name',
        'shortname': 'Short name',
        'status': 'Status',
        'decisionmaker': 'Decision maker'
    
    },
    initComponent: function(){
        Ext.apply(this, {
            border: false,
            title: this.fieldlabels['contactinfo'],
            collapsible: true,
            autoHeight: true,
            defaults: {
                anchor:'100%',
                server: ISales.Connections['server'],
                path: ISales.Connections['path'],
                labelSeparator: ''
            
            },
            defaultType: 'textfield',
            
            items: [{
                fieldLabel: this.fieldlabels['jobtitle'],
                name: 'fdjobtitle'
            
            }, {
                fieldLabel: this.fieldlabels['salutation'],
                xtype: 'keywordcombodirect',
                path: 'dev/i-sales/i-salesprod.nsf',
                key: 'kwcontactsalutation',
                name: 'fdcontactsalutation'
                //hiddenName:'fdcontactsalutation'
            
            }, {
                fieldLabel: this.fieldlabels['firstname'],
                name: 'fdcontactfirstname'
            
            }, {
                fieldLabel: this.fieldlabels['middlename'],
                name: 'fdcontactmiddlename'
            
            }, {
                fieldLabel: this.fieldlabels['lastname'],
                name: 'fdcontactlastname'
            
            }, {
                fieldLabel: this.fieldlabels['shortname'],
                name: 'fdcontactshortname'
            
            }, {
                fieldLabel: this.fieldlabels['status'],
                xtype: 'keywordcombodirect',
                name: 'fdcontactstatus',
                path: 'dev/i-sales/i-salesprod.nsf',
                key: 'kwcontactstatus'
            
            }, {
                xtype: 'xcheckbox',
                boxLabel: this.fieldlabels['decisionmaker'],
                name: 'fddecisionmaker'
            
            }]
        })
        ISales.fieldsets.Contactinfo.superclass.initComponent.apply(this, arguments);
    }
})
Ext.reg('fieldsetcontactinfo', ISales.fieldsets.Contactinfo);

ISales.fieldsets.ContactMailings = Ext.extend(Ext.form.FieldSet, {

    fieldlabels: {
        'mailings': 'Mailings',
        'prevent': 'Prevent mailings',
        'mailgroups': 'Mail groups',
        'history': 'Campagne history'
    
    },
    initComponent: function(){
        Ext.apply(this, {
            border: false,
            title: this.fieldlabels['mailings'],
            collapsible: true,
            autoHeight: true,
            defaults: {
                width: 210,
                server: ISales.Connections['server'],
                path: ISales.Connections['path'],
                labelSeparator: ''
            
            },
            defaultType: 'textfield',
            
            items: [{
                xtype: 'xcheckbox',
                boxLabel: this.fieldlabels['prevent'],
                name: 'fdpreventmailings'
            
            }, {
                fieldLabel: this.fieldlabels['mailgroups'],
                name: 'fdcontactmailgroups',
                xtype: 'keywordmultiselector',
                
                classField: 'cls',
                stackItems: true,
                extraItemCls: 'superboxitem-withicons',
                displayFieldTpl: '<B>{fdalias}</B>',
                kw: 'kwmailgroups',
                listCls: 'orangeBullet'
            }, {
                xtype: 'textarea',
                disabled: true,
                fieldLabel: this.fieldlabels['history'],
                name: 'fdcampaignhistory',
                disabledClass: 'textarea-disabled',
                border: false,
                anchor: '100%',
                grow: true,
                submitValue: false
            }]
        })
        ISales.fieldsets.ContactMailings.superclass.initComponent.apply(this, arguments);
    }
})
Ext.reg('fieldsetcontactmailings', ISales.fieldsets.ContactMailings);


ISales.fieldsets.ContactDetails = Ext.extend(Ext.form.FieldSet, {

    fieldlabels: {
        'contactdetails': 'Contact details',
        'phone': 'Direct phone',
        'cellphone': 'Cell phone',
        'fax': 'Fax',
        'email': 'E-mail',
        'businessfunction': 'Business function',
        'leadsource': 'Lead source'
    
    },
    initComponent: function(){
        Ext.apply(this, {
            border: false,
            title: this.fieldlabels['contactdetails'],
            labelSeparator: '',
            collapsible: true,
            autoHeight: true,
            defaults: {
                anchor:'100%',
                server: ISales.Connections['server'],
                path: ISales.Connections['path'],
                labelSeparator: ''
            
            
            },
            defaultType: 'textfield',
            
            items: [{
            
                fieldLabel: this.fieldlabels['phone'],
                name: 'fdcontactphone'
            
            }, {
                fieldLabel: this.fieldlabels['cellphone'],
                name: 'fdcontactcellphone'
            
            }, {
                fieldLabel: this.fieldlabels['fax'],
                name: 'fdcontactfax'
            
            }, {
                fieldLabel: this.fieldlabels['email'],
                name: 'fdcontactemail'
            
            }, {
                fieldLabel: this.fieldlabels['businessfunction'],
                name: 'fdbusinessfunction',
                xtype: 'keywordcombodirect',
                key: 'kwbusinessfunction'
            
            }, {
                fieldLabel: this.fieldlabels['leadsource'],
                xtype: 'keywordcombodirect',
                name: 'fdcontactleadorig',
                key: 'kwleadsource'
            
            }]
        })
        ISales.fieldsets.ContactDetails.superclass.initComponent.apply(this, arguments);
    }
})

Ext.reg('fieldsetcontactdetails', ISales.fieldsets.ContactDetails);

//Ext.reg('companyformtabs', ISales.CompanyFormTabs);

ISales.CompanyTabPanel = Ext.extend(Ext.TabPanel, {
    tabnames: {
        'information': 'Information',
        'clContactProfile': 'Contacts',
        'clActivity': 'Activities',
        'clDocument': 'Documents',
        'clEmail': 'E-Mail'
    },
    
    initComponent: function(){
        Ext.apply(this, {
            plain: true,
            enableTabScroll: true,
            hideBorders: true,
            activeTab: 0,
            items: [{
                xtype: 'panel',
                id: 'tab-companyformtabs-' + this.unid,
                bodyStyle: 'padding:10px;',
                iconCls: '',
                autoScroll: true,
                // layout: 'fit',
                title: this.tabnames['information'],
                items: [{
                    xtype: 'fieldsetcategories',
                    titleCollapse: true,
                    collapsed: true,
                    border: false
                
                }, {
                    xtype: 'fieldsetresponsible',
                    titleCollapse: true,
                    collapsed: true,
                    border: false
                
                }]
            }, {
                xtype: 'contacts',
                id: 'tab-clContactProfile-' + this.unid,
                iconCls: 'clContactProfile',
                title: this.tabnames['clContactProfile'],
                unid: this.unid
            }, {
                xtype: 'documents',
                id: 'tab-clDocument-' + this.unid,
                title: this.tabnames['clDocument'],
                unid: this.unid
            }, {
                xtype: 'emails',
                id: 'tab-clEmail-' + this.unid,
                title: this.tabnames['clEmail'],
                unid: this.unid
            }, {
                xtype: 'activities',
                id: 'tab-clActivity-' + this.unid,
                title: this.tabnames['clActivity'],
                unid: this.unid
            }]
        })
        ISales.CompanyTabPanel.superclass.initComponent.apply(this, arguments);
        this.on('render', this.updateTabTotals, this)
        
    },
    updateTabTotals: function(t){
        //Load Contacts store
        Ext.getCmp('tab-clContactProfile-' + this.unid).getStore().load()
        
        //Ext.getCmp('tab-clDocument-' + this.unid).on('activate', function(){this.getStore().load()},Ext.getCmp('tab-clDocument-' + this.unid))
        
        Domino.getTabCount("", "dev/i-sales/i-salesprod.nsf", this.unid, function(provider, response){
            Ext.each(provider, function(v){
                Entry = Ext.getCmp('tab-' + v.cls + '-' + this.unid)
                if (Entry) {
                    Entry.setTitle(this.tabnames[v.cls] + ' (' + v.cnt + ')')
                }
            }, this);
        }, this);
    }
})

Ext.reg('companytabpanel', ISales.CompanyTabPanel);

ISales.ContactProfile = Ext.extend(ExtArc.Form, {
    doctype: 'clContactProfile',
    i18n: {
        'save': 'Save',
        'cancel': 'Cancel',
        'newDocumentTitle': 'New Contact'
    
    },
    tabnames: {
        'information': 'Information',
        'mailings': 'Mailings'
    },
    
    initComponent: function(){
        Ext.apply(this, {
            labelAlign: 'left',
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            border: false,
            items: [{
                border: false,
                height: 2
            }, {
                xtype: 'tabpanel',
                plain: true,
                hideBorders: true,
                activeTab: 0,
                
                flex: 1,
                border: false,
                items: [{
                    title: this.tabnames['information'],
                    
                    layout: {
                        type: 'hbox',
                        align: 'stretch'
                    },
                    items: [{
                        flex: 1,
                        border: false,
                        autoScroll: true,
                        bodyStyle: 'padding-top:8px;',
                        items: [{
                            xtype: 'fieldsetcontactinfo'
                        }]
                    }, {
                        flex: 1,
                        border: false,
                        bodyStyle: 'padding-top:8px;',
                        
                        autoScroll: true,
                        items: [{
                            xtype: 'fieldsetcontactdetails'
                        }]
                    }]
                }, {
                    title: this.tabnames['mailings'],
                    autoScroll: true,
                    bodyStyle: 'padding-top:8px;',
                    border: false,
                    items: [{
                    
                        xtype: 'fieldsetcontactmailings'
                    }]
                
                }]
            }]
        })
        ISales.ContactProfile.superclass.initComponent.apply(this, arguments);
        this.on('onLoadSuccess', this.LoadSuccess, this)
        this.on('onSaveSuccess', this.SaveSuccess, this)
        this.on('onCancelClick', this.Cancel, this)
        this.on('onNewDocument', this.NewDocument, this)
    },
    LoadSuccess: function(action){
        this.setTitle(Ext.util.Format.ellipsis(action.result.data['fddocumentdescription'], 20))
        this.setIconClass(this.iconClass)
        this.dragZone = new Ext.dd.DragSource(this.findParentByType(Ext.TabPanel).getTabEl(this), {
            ddGroup: 'FavDD',
            getDragData: this.GetDragData.createDelegate(this, action, true),
            getRepairXY: function(){
                return this.dragData.repairXY;
            }
        });
    },
    GetDragData: function(e, action){
        this.show()
        var sourceEl = e.getTarget('span');
        if (sourceEl) {
            d = sourceEl.cloneNode(true);
            d.id = Ext.id();
            return {
                sourceEl: d,
                repairXY: Ext.fly(sourceEl).getXY(),
                ddel: d,
                tabData: {
                    fdTargetDocumentKey: action.result.data['fddocumentkey'],
                    fdDocumentDescription: action.result.data['fdcontactname'],
                    fdDocumentClass: 'clContactProfile'
                }
            }
        }
    },
    SaveSuccess: function(action){
        this.loadform()
    },
    Cancel: function(){
    
    },
    NewDocument: function(newtitle){
        this.setTitle(Ext.util.Format.ellipsis(newtitle, 20))
        this.setIconClass(this.iconClass)
        
    },
    onDestroy: function(){
        this.dragZone.destroy()
    }
})
Ext.reg('clContactProfile', ISales.ContactProfile);

Ext.override(Ext.form.HtmlEditor, {
    /**
     * Set a readonly mask over the editor
     * @param {Boolean} readOnly - True to set the read only property, False to switch to the editor
     */
    setReadOnly: function(readOnly){
        if (readOnly) {
            this.syncValue();
            var roMask = this.wrap.mask();
            roMask.dom.style.filter = "alpha(opacity=100);"; //IE
            roMask.dom.style.opacity = "1"; //Mozilla
            roMask.dom.style.background = "white";
            roMask.dom.style.overflow = "scroll";
            roMask.dom.innerHTML = this.getValue();
            this.el.dom.readOnly = true;
        }
        else {
            if (this.rendered) {
                this.wrap.unmask();
            }
            this.el.dom.readOnly = false;
        }
    }
});


ISales.Email = Ext.extend(ExtArc.Form, {
    doctype: 'clEmail',
    i18n: {
        'save': 'Save',
        'cancel': 'Cancel',
        'newDocumentTitle': 'New Email'
    
    },
    tabnames: {
        'information': 'EMail',
        'category': 'Categorization'
    },
    
    initComponent: function(){
        Ext.apply(this, {
            labelAlign: 'left',
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            border: false,
            items: [{
                height: 50,
                
                border: false,
                layout: 'form',
                labelAlign: 'left',
                defaults: {
                    anchor: '100%',
                    xtype: 'textfield',
                    disableWhenSaved: true
                },
                items: [{
                    fieldLabel: 'To',
                    name: 'fdemailto'
                
                }, {
                    fieldLabel: 'Subject',
                    name: 'fdsubject'
                }]
            }, {
                flex: 1,
                border: false,
                layout: 'form',
                labelAlign: 'top',
                items: [{
                    disableWhenSaved: false,
                    anchor: '100% 100%',
                    xtype: 'htmleditor',
                    enableAlignments: false,
                    name: 'fdbody',
                    setReadOnly: true
                }]
            }]
        })
        ISales.Email.superclass.initComponent.apply(this, arguments);
        this.on('onLoadSuccess', this.LoadSuccess, this)
        this.on('onSaveSuccess', this.SaveSuccess, this)
        this.on('onCancelClick', this.Cancel, this)
        this.on('onNewDocument', this.NewDocument, this)
    },
    LoadSuccess: function(action){
        this.setTitle(Ext.util.Format.ellipsis(action.result.data['fddocumentdescription'], 20))
        this.setIconClass(this.iconClass)
        
        // Disable fields if fdsentdate has a date
        if (action.result.data['fddocumentdescription']) {
            this.getForm().items.each(function(v){
                if (v.disableWhenSaved) {
                    v.setDisabled(true)
                }
                else 
                    if (v.setReadOnly) {
						this.border=false
                        //console.log(v)
                        v.syncValue();
                        var roMask = v.wrap.mask();
                        roMask.dom.style.filter = "alpha(opacity=100);"; //IE
                        roMask.dom.style.opacity = "1"; //Mozilla
                        roMask.dom.style.background = "white";
						roMask.border=false;
                        roMask.dom.style.overflow = "auto";
						//roMask.dom.style.padding = "8px";
						
                        roMask.dom.innerHTML = v.getValue();
                        v.el.dom.readOnly = true;
                    }
            });
        }
        
        
        this.dragZone = new Ext.dd.DragSource(this.findParentByType(Ext.TabPanel).getTabEl(this), {
            ddGroup: 'FavDD',
            getDragData: this.GetDragData.createDelegate(this, action, true),
            getRepairXY: function(){
                return this.dragData.repairXY;
            }
        });
    },
    GetDragData: function(e, action){
        this.show()
        var sourceEl = e.getTarget('span');
        if (sourceEl) {
            d = sourceEl.cloneNode(true);
            d.id = Ext.id();
            return {
                sourceEl: d,
                repairXY: Ext.fly(sourceEl).getXY(),
                ddel: d,
                tabData: {
                    fdTargetDocumentKey: action.result.data['fddocumentkey'],
                    fdDocumentDescription: action.result.data['fdsubject'],
                    fdDocumentClass: 'clEmail'
                }
            }
        }
    },
    SaveSuccess: function(action){
        this.loadform()
    },
    Cancel: function(){
    
    },
    NewDocument: function(newtitle){
        this.setTitle(Ext.util.Format.ellipsis(newtitle, 20))
        this.setIconClass(this.iconClass)
        
    },
    onDestroy: function(){
        this.dragZone.destroy()
    }
})
Ext.reg('clEmail', ISales.Email);

ISales.CompanyProfile = Ext.extend(ExtArc.Form, {

    doctype: 'clCompanyProfile',
    i18n: {
        'save': 'Save',
        'cancel': 'Cancel',
        'newDocumentTitle': 'New Document'
    
    },
    fieldlabels: {
        'country': 'Country',
        'companyname': 'Company'
    },
    tabnames: {
        'companyformtabs': 'Information',
        'clContactProfile': 'Contacts',
        'clActivity': 'Activities',
        'clDocument': 'Documents',
        'clEmail': 'E-Mail'
    },
    
    initComponent: function(){
    
    
        Ext.apply(this, {
            cls: 'yellowBackground',
            
            labelAlign: 'left',
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            items: [{
                height: 40,
                xtype: 'panel',
                border: false,
                layout: {
                    type: 'hbox',
                    align: 'stretch'
                },
                defaults: {
                    border: false
                },
                items: [{
                    width: 20,
                    border: false,
                    bodyCssClass: 'yellowBackground',
                    html: '<IMG SRC=/web/i-sales/theme1/IMAGES/icon_clCompanyProfile.gif>'
                }, {
                    xtype: 'panel',
                    layout: 'form',
                    bodyCssClass: 'yellowBackground',
                    flex: 1,
                    labelWidth: 1,
                    defaults: {
                        anchor: '100%',
                        xtype: 'textfield'
                    },
                    items: [{
                        name: 'fdcompanyname'
                        //fieldLabel: this.fieldlabels['companyname']
                    }]
                
                }, {
                
                    xtype: 'panel',
                    layout: 'form',
                    bodyCssClass: 'yellowBackground',
                    flex: 1,
                    defaults: {
                        anchor: '100%',
                        xtype: 'textfield'
                    },
                    items: [{
                        xtype: 'keywordcombodirect',
                        name: 'fdcompanycountrytext',
                        hiddenName: 'fdcompanycountry',
                        fieldLabel: this.fieldlabels['country'],
                        server: ISales.Connections['server'],
                        path: ISales.Connections['path'],
                        key: 'kwCountryList'
                    }]
                }]
            }, {
            
                flex: 1,
                border: true,
                xtype: 'companytabpanel',
                tabnames: this.tabnames,
                id: 'tabpanel-' + this.unid,
                unid: this.unid
            
            }]
        
        });
        ISales.CompanyProfile.superclass.initComponent.apply(this, arguments);
        this.on('onLoadSuccess', this.LoadSuccess, this)
        this.on('onSaveSuccess', this.SaveSuccess, this)
        this.on('onCancelClick', this.Cancel, this)
        this.on('onNewDocument', this.NewDocument, this)
    },
    LoadSuccess: function(action){
        this.setTitle(Ext.util.Format.ellipsis(action.result.data['fddocumentdescription'], 20))
        this.setIconClass(this.iconClass)
        this.dragZone = new Ext.dd.DragSource(this.findParentByType(Ext.TabPanel).getTabEl(this), {
            ddGroup: 'FavDD',
            getDragData: this.GetDragData.createDelegate(this, action, true),
            getRepairXY: function(){
                return this.dragData.repairXY;
            }
        });
    },
    GetDragData: function(e, action){
        this.show()
        var sourceEl = e.getTarget();
        if (sourceEl) {
            d = sourceEl.cloneNode(true);
            d.id = Ext.id();
            return {
                sourceEl: d,
                repairXY: Ext.fly(sourceEl).getXY(),
                ddel: d,
                tabData: {
                    fdTargetDocumentKey: action.result.data['fddocumentkey'],
                    fdDocumentDescription: action.result.data['fdcompanyname'],
                    fdDocumentClass: 'clCompanyProfile'
                }
            }
        }
    },
    SaveSuccess: function(action){
        this.loadform()
    },
    Cancel: function(){
    
    },
    NewDocument: function(newtitle){
        this.setTitle(Ext.util.Format.ellipsis(newtitle, 20))
        this.setIconClass(this.iconClass)
        
    },
    onDestroy: function(){
        this.dragZone.destroy()
    }
    
});
Ext.reg('clCompanyProfile', ISales.CompanyProfile);

ISales.grids.Emails = Ext.extend(Ext.grid.GridPanel, {
    initComponent: function(){
        Ext.apply(this, {
            enableDragDrop: true,
            ddGroup: 'FavDD',
            store: new Ext.data.DirectStore({
                //paramsAsHash: false,
                paramOrder: ['server', 'path', 'parentunid', 'doctype', 'returnfields'],
                
                directFn: CRUD.CrudRead,
                
                baseParams: {
                    server: ISales.Connections['server'],
                    path: ISales.Connections['path'],
                    parentunid: this.unid,
                    doctype: 'clEmail',
                    returnfields: 'fddocumentkey, fddocumentdescription, fdemailfrom, fdemailto, fdsentdate, fddocumentclass'
                },
                reader: new Ext.data.JsonReader({
                    totalProperty: 'total',
                    successProperty: 'success',
                    idProperty: 'fddocumentkey',
                    root: 'data'
                }, [{
                    name: 'fddocumentkey'
                }, {
                    name: 'fddocumentdescription'
                }, {
                    name: 'fdemailfrom'
                }, {
                    name: 'fdemailto'
                }, {
                    name: 'fdsentdate',
                    type: 'date',
                    dateFormat: 'c'
                }, {
                    name: 'fddocumentclass'
                }]),
                remoteSort: false
            }),
            columns: [{
                header: 'date',
                dataIndex: 'fdsentdate',
                sortable: true
            
            }, {
                header: 'From',
                dataIndex: 'fdemailfrom'
            }, {
                header: 'To',
                dataIndex: 'fdemailto'
            }, {
                header: "description",
                dataIndex: 'fddocumentdescription'
            }],
            selModel: new Ext.grid.RowSelectionModel(),
            view: new Ext.grid.GridView({
                forceFit: true,
                startCollapsed: true
            })
        })
        ISales.grids.Emails.superclass.initComponent.apply(this, arguments);
        this.on('rowdblclick', this.openMail, this)
        this.on('activate', function(){
            this.getStore().load()
        }, this)
    },
    openMail: function(grid, row, e){
        var record = grid.getStore().getAt(row);
        ISalesGlobal.ui.OpenFromSearchView('clEmail', record.data.fddocumentkey, '')
    }
    
});
Ext.reg('emails', ISales.grids.Emails);

ISales.grids.Documents = Ext.extend(Ext.grid.GridPanel, {
    columnnames: {
        'description': 'Description'
    },
    initComponent: function(){
        Ext.apply(this, {
            enableDragDrop: true,
            ddGroup: 'FavDD',
            store: new Ext.data.DirectStore({
                //paramsAsHash: false,
                paramOrder: ['server', 'path', 'parentunid', 'doctype', 'returnfields'],
                
                directFn: CRUD.CrudRead,
                
                baseParams: {
                    server: ISales.Connections['server'],
                    path: ISales.Connections['path'],
                    parentunid: this.unid,
                    doctype: 'clDocument',
                    returnfields: 'fddocumentkey, fddocumentdescription, fddocumentclass'
                },
                reader: new Ext.data.JsonReader({
                    totalProperty: 'total',
                    successProperty: 'success',
                    idProperty: 'fddocumentkey',
                    root: 'data'
                }, [{
                    name: 'fddocumentkey'
                }, {
                    name: 'fddocumentdescription'
                }, {
                    name: 'fddocumentclass'
                }]),
                remoteSort: false
            }),
            columns: [{
                header: this.columnnames['description'],
                dataIndex: 'fddocumentdescription'
            }],
            selModel: new Ext.grid.RowSelectionModel(),
            view: new Ext.grid.GridView({
                forceFit: true,
                startCollapsed: true
            })
        })
        ISales.grids.Documents.superclass.initComponent.apply(this, arguments);
        this.on('activate', function(){
            this.getStore().load()
        }, this)
    }
    
});
Ext.reg('documents', ISales.grids.Documents);

ISales.grids.Activities = Ext.extend(Ext.grid.GridPanel, {

    initComponent: function(){
        Ext.apply(this, {
            enableDragDrop: true,
            ddGroup: 'FavDD',
            store: new Ext.data.GroupingStore({
                //paramsAsHash: false,
                proxy: new Ext.data.DirectProxy({
                    paramsAsHash: false,
                    paramOrder: ['server', 'path', 'parentunid', 'doctype', 'returnfields'],
                    directFn: CRUD.CrudRead
                }),
                baseParams: {
                    server: ISales.Connections['server'],
                    path: ISales.Connections['path'],
                    parentunid: this.unid,
                    doctype: 'clActivity',
                    returnfields: 'fddocumentkey, fddocumentdescription, fdactivitytype, fddocumentclass'
                },
                reader: new Ext.data.JsonReader({
                    totalProperty: 'total',
                    successProperty: 'success',
                    idProperty: 'fddocumentkey',
                    root: 'data'
                }, [{
                    name: 'fddocumentkey'
                }, {
                    name: 'fddocumentdescription'
                }, {
                    name: 'fdactivitytype'
                
                }, {
                    name: 'fddocumentclass'
                
                }]),
                sortInfo: {
                    field: 'fddocumentdescription',
                    direction: 'DESC'
                },
                groupField: 'fdactivitytype'
            }),
            columns: [{
                header: '',
                dataIndex: 'fdactivitytype',
                renderer: this.activityRenderer
            
            }, {
                header: "description",
                dataIndex: 'fddocumentdescription'
            }],
            selModel: new Ext.grid.RowSelectionModel(),
            view: new Ext.grid.GroupingView({
                forceFit: true,
                startCollapsed: true,
                hideGroupedColumn: true,
                groupTextTpl: '{text} ({[values.rs.length]}' + ' ' + ISales.Labels['items'] + ')'
            })
        })
        ISales.grids.Activities.superclass.initComponent.apply(this, arguments);
        this.on('activate', function(){
            this.getStore().load()
        }, this)
    },
    activityRenderer: function(value, metaData, record, rowIndex, colIndex, store){
        return ISales.ActivityNames[value]
    }
    
});
Ext.reg('activities', ISales.grids.Activities);

ISales.grids.Contacts = Ext.extend(Ext.grid.GridPanel, {
    cls: 'nolinegrid noheader',
    initComponent: function(){
        Ext.apply(this, {
            enableDragDrop: true,
            ddGroup: 'FavDD',
            store: new Ext.data.DirectStore({
                //paramsAsHash: false,
                paramOrder: ['server', 'path', 'parentunid', 'doctype', 'returnfields'],
                api: {
                    read: CRUD.CrudRead,
                    create: CRUD.CrudCreate,
                    update: CRUD.CrudUpdate,
                    destroy: CRUD.CrudDestroy
                
                },
                baseParams: {
                    server: ISales.Connections['server'],
                    path: ISales.Connections['path'],
                    parentunid: this.unid,
                    doctype: 'clContactProfile',
                    returnfields: 'fddocumentkey, fddocumentdescription, fddocumentclass'
                },
                reader: new Ext.data.JsonReader({
                    totalProperty: 'total',
                    successProperty: 'success',
                    idProperty: 'fddocumentkey',
                    root: 'data'
                }, [{
                    name: 'fddocumentkey'
                }, {
                    name: 'fddocumentdescription'
                }, {
                    name: 'fddocumentclass'
                }]),
                batchSave: false,
                //prettyUrls: false,
                remoteSort: false
            }),
            columns: [{
                header: "description",
                dataIndex: 'fddocumentdescription',
                editor: new Ext.form.TextField({
                    selectOnFocus: true
                })
            }],
            selModel: new Ext.grid.RowSelectionModel(),
            view: new Ext.grid.GridView({
                forceFit: true,
                startCollapsed: true
            })
        })
        ISales.grids.Contacts.superclass.initComponent.apply(this, arguments);
        this.on('rowdblclick', this.openContact, this)
        //this.getStore().on('beforewrite', this.bw, this)
    },
    bw: function(t, opt){
        //t.paramOrder = ['server', 'path', 'parentunid', 'id', 'records'];
    },
    openContact: function(grid, row, e){
        var record = grid.getStore().getAt(row);
        ISalesGlobal.ui.OpenFromSearchView('clContactProfile', record.data.fddocumentkey, '')
    }
    
})
Ext.reg('contacts', ISales.grids.Contacts);


/*


 kalle = new Ext.TabPanel({


 height: 200,


 width: 300,


 activeTab: 0,


 items: [{


 title: 'Tab 1'


 }, {


 title: 'Tab 2'


 }, {


 title: 'Tab 3'


 }],


 listeners: {


 render: function(c){


 c.editor = new Ext.Editor(new Ext.form.TextField({


 allowBlank: false,


 enterIsSpecial: true


 }), {


 autoSize: 'width',


 completeOnEnter: true,


 cancelOnEsc: true,


 listeners: {


 complete: function(editor, value){


 var item = this.getComponent(editor.boundEl.id.split(this.idDelimiter)[1]);


 item.setTitle(value);


 },


 scope: c


 }


 });


 c.mon(c.strip, {


 dblclick: function(e){


 var t = this.findTargets(e);


 if (t && t.item && !t.close) {


 this.editor.startEdit(t.el, t.item.title);


 }


 },


 scope: c


 });


 }


 },


 renderTo: Ext.getBody()


 });


 */


